<template>
  <div class="real-time-data">
    <div class="head-button mb-15px">
      <el-button
          type="primary"
          size="middle"
          :class="{ 'mr-10px': true, gray: !showAlarmList }"
          @click="showAlarmList = !showAlarmList"
      >报警信息
      </el-button>
      <div
          class="cursor-pointer"
          @click="fullscreen"
      >
        <icon :size="32" type="icon-zuidahua"/>
      </div>
    </div>
    <div class="body">
      <div class="left">
        <div class="head">
          <span :class="{ selected: curTab === 'floor' }" @click="selectLeftTab('floor')"
          >按楼层</span
          >
          <span :class="{ selected: curTab === 'info' }" @click="selectLeftTab('info')"
          >按信息</span
          >
        </div>
        <div v-if="curTab === 'floor'" class="body">
          <el-tree
              @current-change="onSelect"
              :props="{  children: 'children',  label: 'constName',}"
              :data="bedRealTimeData.floorList"
          >
          </el-tree>
        </div>
        <div v-if="curTab === 'info'" class="body">
          <div>
            <el-input
                v-model="infoFilter.olderName"
                @change="olderChange"
                placeholder="请输入姓名"
            />
          </div>
          <p class="mt-20px mb-10px" style="display: none">床位状态</p>
          <div class="bed-btn-group" style="display: none">
            <span
                v-for="(item, index) in infoFilter.bedStatusButtons"
                :key="index"
                :class="{ 'bed-btn': true, selected: item.selected }"
                @click="selectedBedBtn(item)"
            >{{ item.label }}</span
            >
          </div>
        </div>
      </div>
      <div id="realTimeData" ref="autoLayoutRef" class="center">
        <!--'alarm-item-4':showAlarmList,'alarm-item-5':!showAlarmList-->
        <div
            v-for="_ in bedRealTimeData.dataList"
            :key="_.id"
            :class="{ 'alarm-item': true }"
            :style="state.customStyle"
        >
          <div
              :class="{
              head: true,
              'alarm-head': _.status === 'alarm',
              'warn-head': _.status === 'warn',
              'normal-head': _.status === 'normal',
              'offline-head': _.status === 'offline',
            }"
              @click="openHistoryData(_)"
          >
            <span>
              <icon :size="15" type="icon-a-zu2569"/>
              {{ _.bedName || '--' }}
            </span>
            <span>
              {{ `${_.older || '--'}-${_.sex === 1 ? '男' : '女'}-${_.age || '--'}岁` }}
            </span>
            <span>
              <icon :size="15" type="icon-a-zu2761"/>
            </span>
          </div>
          <div class="body">
            <div class="head">
              <span class="mr-10px">健康数据</span>
              <span class="mr-10px">
                <icon :size="21" type="icon-a-zu1662"/>
              </span>
              <div class="status">
                <span
                    v-for="(item, index) in _.exceptions || []"
                    :key="index"
                    :class="{
                    'warn-bg': item.state === 'warn',
                    'alarm-bg': item.state === 'alarm',
                    'mr-5px': true,
                  }"
                >{{ item.name }}</span
                >
              </div>
            </div>
            <!--床垫状态或报警区域  1:正常 0：警告 -1：报警-->
            <div class="status-div">
              <div class="normal">
                <span>
                  <icon :size="22" type="icon-a-zu2200"/>
                  <span :class="{ text: true, 'red-color': _.somaticData.heartRateHigh }">{{
                      _.somaticData.heartRate || '--'
                    }}</span>
                  <span class="unit">次/分</span>
                </span>
                <span>
                  <icon :size="22" type="icon-a-zu2196"/>
                  <span
                      class="text"
                      :class="{ text: true, 'red-color': _.somaticData.breatheHigh }"
                  >
                    {{ _.somaticData.breathe || '--' }}
                  </span>
                  <span class="unit">次/分</span>
                </span>
                <span>
                  <icon :size="22" type="icon-a-zu2771"/>
                  <span :class="{ text: true, 'red-color': _.somaticData.temperatureHigh }">
                    {{ _.somaticData.temperature || '--' }}
                  </span>
                  <span class="unit">℃</span>
                </span>
                <span>
                  <icon :size="22" type="icon-a-zu2194"/>
                  <span :class="{ text: true, 'red-color': _.somaticData.bloodOxygenHigh }">{{
                      _.somaticData.bloodOxygen || '--'
                    }}</span>
                  <span class="unit">%</span>
                </span>
                <span>
                  <icon :size="22" type="icon-a-zu2199"/>
                  <span :class="{ text: true, 'red-color': _.somaticData.bloodPressureHigh }">{{
                      _.somaticData.bloodPressure || '--'
                    }}</span>
                  <span class="unit">mmHg</span>
                </span>
                <span>
                  <icon :size="22" type="icon-a-zu2760"/>
                  <span :class="{ text: true, 'red-color': _.somaticData.bloodSugarHigh }">{{
                      _.somaticData.bloodSugar || '--'
                    }}</span>
                  <span class="unit">mmol/L</span>
                </span>
              </div>
              <div class="time-div">
                <div v-if="_.rollOverTime" class="roll-over">
                  <span>翻身倒计:</span>
                  <span>{{ _.rollOverTime }}</span>
                </div>
                <p><span>更新时间:</span>{{ _.updateTime || '--' }}</p>
              </div>
            </div>
            <a-divider style="border-color: #c6cad1" dashed/>
            <!--设备状态或报警区域  1:正常 0：警告 -1：报警-->
            <div class="bottom">
              <div class="head">
                <span>设备状况</span>
              </div>
              <div class="body">
                <!--设备状况不显示床垫-->
                <div
                    v-for="(device, index) in _.deviceList.filter((i) => i.deviceTypeName !== '床垫')"
                    :key="index"
                >
                  <span>{{ device.deviceTypeName }}:</span>
                  <span
                      :class="{
                      'red-color': device.status === 'alarm',
                      'gray-color': device.status === 'normal',
                    }"
                  >{{ device.status === 'normal' ? '正常' : '异常' }}</span
                  >
                </div>
              </div>
              <div class="update-time">更新:{{ _.deviceUpdateTime || '--' }}</div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="showAlarmList" class="right-alarm">
        <div class="head">
          <span>异常报警列表</span>
          <span class="cursor-pointer" @click="showAlarmList = false">收起>></span>
        </div>
        <div class="body">
          <div
              v-for="(item, index) in alarmListData.data"
              :key="item.id || index"
              class="alarm-list-item"
          >
            <div class="alarm-list-item-content">
              <div class="item-content-left">
                <span
                    v-if="item.type === 1"
                    :class="{ tag: true, gray: item.disposed, green: !item.disposed }"
                >人员</span
                >
                <span
                    v-else-if="item.type === 2"
                    :class="{ tag: true, gray: item.disposed, blue: !item.disposed }"
                >设备</span
                >
              </div>
              <div class="item-content-right">
                <el-tooltip placement="topLeft">
                  <template #title>
                    <span>{{ item.bedName }}{{ item.olderName }}</span>
                  </template>
                  <span :class="{ 'gray-color': item.disposed, 'black-color': !item.disposed }"
                  >{{ item.bedName }}{{ item.olderName }}</span
                  >
                </el-tooltip>
                <el-tooltip placement="topLeft">
                  <template #title>
                    <span>{{ item.alarmText }}</span>
                  </template>
                  <span :class="{ 'gray-color': item.disposed, 'red-color': !item.disposed }">{{
                      item.alarmText
                    }}</span>
                </el-tooltip>
              </div>
            </div>
            <span
                :class="{ 'gray-color': item.disposed, 'blue-color': !item.disposed, 'handle-class': true }"
                @click="earlyHandle(item)"
            >{{ item.disposed ? '已处理' : '处理' }}</span
            >
          </div>
        </div>
      </div>
    </div>

    <DynamicDialog ref="dynamicHistoryDialogRef" @click="callBackHistory" :button="{confirm:false}"
                   :dialogVisible="state.openHistoryDataVisible"
                   title="数据展示" width="80%">
      <template #dialog>
        <HistoryData ref="historyDataRef" v-if="state.openHistoryDataVisible" :older="state.curOlder"/>
      </template>
    </DynamicDialog>


    <DynamicDialog ref="dynamicDialogRef" @click="callBack" :dialogVisible="state.dialogVisible" :button="state.button"
                   title="预警处理" width="50%">
      <template #dialog>
        <DynamicForm ref="dynamicFormRef" v-if="state.dialogVisible" @click="callBack" :rulesForm="state.rulesForm"
                     :rules="state.rules"
                     width="500px"/>
      </template>
    </DynamicDialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {useFullscreen} from '@vueuse/core';

import HistoryData from './history/Index.vue'
import DynamicForm from '@/components/layout/form/dynamic-form.vue'
import DynamicDialog from '@/components/layout/dialog/dynamic-dialog.vue'

import {IconFont} from "@/components/iconfont";

import {earlyHandleApi, listPersonnelApi,} from '@/api/personnel/index';
import {listFindByBmsConstVoApi} from '@/api/dictionary';
import {listBmsBedApi} from '@/api/bed';
import {intelligenceAdaptiveLayout} from "@/utils/consts/alarm";
import {getAgeByIDCard} from "@/utils/common";
import {sendRealTimeSocket} from "@/assets/script/monitor/real-time";
import {rules, rulesForm} from '@/assets/script/monitor/forms/home/early-proces-from';
import {ElMessage} from "element-plus";

const dynamicHistoryDialogRef = ref(DynamicDialog)
const dynamicDialogRef = ref(DynamicDialog)
const dynamicFormRef = ref(DynamicForm)
const historyDataRef = ref(HistoryData)

const icon = IconFont
const curTab = ref('floor');
let dom = {} as HTMLElement;
const autoLayoutRef = ref();
const state = reactive({
  customStyle: {} as any,
  curOlder: {},
  openHistoryDataVisible: false,
  dialogVisible: false,
  handleData: {} as any,
  button: {
    cancel: false,
    confirm: false,
  },
  rulesForm: [] as any,
  rules: rules
});
/**
 * 床数据(真正用于展示的数据)
 * */
const bedRealTimeData = reactive({
  data: [] as any,
  dataList: [] as any,
  floorList: [] as any,
});
/**
 * 右侧报警列表
 * */
const alarmListData = reactive({
  data: [],
}) as any;
onMounted(() => {
  // 请求人员床位数据
  getBedData();
  // 楼层
  getFloor();
  //布局自适应
  layoutAdaptive();
});

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'dialogClose':
      state.dialogVisible = false
      break
    case 'submit':
      console.log(data)
      earlyHandleEvent(data.data)
      break
    default:
      break
  }
}
const callBackHistory = (data: any) => {
  switch (data.type || '') {
    case 'dialogClose':
      state.openHistoryDataVisible = false
      break
    default:
      break
  }
}

/** 楼层信息 **/
const getFloor = async () => {
  await listFindByBmsConstVoApi({dictionaryCode: 'floor'}).then((floor) => {
    getRoom(floor);
  });
};
/** 房间信息 **/
const getRoom = async (floorList: any) => {
  let floorCodeList = floorList.map((m: any) => {
    return m.constCode;
  });
  await listFindByBmsConstVoApi({parentCodeList: floorCodeList}).then((room) => {
    for (let i = 0; i < floorList.length; i++) {
      let floor = floorList[i];
      let roomList = room.filter((f: any) => f.parentCode === floor.constCode);
      floor.children = roomList;
    }
    getBed(room, floorList);
  });
};
/** 床位信息 **/
const getBed = async (data: any, floorList: any) => {
  let roomCodeList = data.map((m: any) => {
    return m.constCode;
  });
  await listBmsBedApi({roomCodeList: roomCodeList}).then((bedList) => {
    for (let i = 0; i < data.length; i++) {
      let room = data[i];
      let itemList = bedList.filter((f: any) => f.room === room.constCode);
      room.children = [] as any;
      for (let k = 0; k < itemList.length; k++) {
        let item = itemList[k];
        room.children.push({constName: item.name, constCode: item.id});
      }
    }
    bedRealTimeData.floorList = floorList;
    bedRealTimeData.floorList.unshift({constName: '全部', constCode: '0'})
    console.log('floorList', bedRealTimeData.floorList)
  });
};

const onSelect = async (selectedKeys: any, info: any) => {
  if (selectedKeys.constCode === '0') {
    bedRealTimeData.dataList = bedRealTimeData.data;
    return
  }
  if (selectedKeys.dictionaryCode === 'floor') {
    return;
  }
  if (selectedKeys.dictionaryCode === 'room') {
    bedRealTimeData.dataList = bedRealTimeData.data.filter((f) => f.roomType === selectedKeys.constCode);
  } else {
    bedRealTimeData.dataList = bedRealTimeData.data.filter((f) => f.bedId === selectedKeys.constCode);
  }
  console.log('floorList', bedRealTimeData.dataList);
};
const olderChange = async (value: any) => {
  if (value) {
    bedRealTimeData.dataList = bedRealTimeData.data.filter(
        (f: any) => f.older.indexOf(value) > -1,
    );
  } else {
    bedRealTimeData.dataList = bedRealTimeData.data;
  }
}
/**
 * 获取床位数据
 * */
const getBedData = async () => {
  const testData = ((await listPersonnelApi({})) || []).filter((_) => _.bed.id);
  bedRealTimeData.data = testData.map((_) => {
    return {
      id: _.id,
      bedName: _.bed?.bedName,
      bedId: _.bed?.id,
      roomType: _.bed?.roomType,
      older: _.displayName,
      age: getAgeByIDCard(_.idCard),
      sex: _.sex,
      exceptions: [
        //异常
        // { name: '体动', state: 0 },
        // { name: '失禁', state: 1 },
      ],
      status: 'offline',
      somaticData: {
        heartRate: '--', //心率
        breathe: '--', //呼吸
        temperature: '--', //体温
        bloodOxygen: '--', //血氧
        bloodPressure: '--', //血压
        bloodSugar: '--', //血糖
      },
      rollOverTime: '',
      updateTime: '',
      deviceList: _.deviceList.map((device: any) => {
        return {
          ...device,
          deviceTypeName: device.deviceTypeName,
          status: 'normal',
        };
      }),
      deviceUpdateTime: '',
    };
  });
  bedRealTimeData.dataList = bedRealTimeData.data;
  //请求实时数据socket，并处理
  await sendRealTimeSocket(bedRealTimeData.data, alarmListData.data, () => {
  });
};
/**
 * 报警处理
 * */
const earlyHandle = async (record: any) => {
  if (record.disposed === true) {
    return;
  }
  state.rulesForm = JSON.parse(JSON.stringify(rulesForm))
  state.dialogVisible = true
  state.handleData = record
};

const earlyHandleEvent = (values: any) => {
  const {id, deviceCode, alarmType, deviceType, olderId} = state.handleData
  values['id'] = id
  values['deviceCode'] = deviceCode
  values['alarmType'] = alarmType
  values['deviceType'] = deviceType
  values['olderId'] = olderId
  if (!values['enclosure']) {
    values['enclosure'] = []
  }
  earlyHandleApi(values).then(r => {
    if (r.code === 0) {
      state.dialogVisible = false
      state.handleData['disposed'] = true;
      ElMessage.success('处理成功！')
    } else {
      ElMessage.warning('处理失败！')
      console.log(r)
    }
  })
}

/**
 * 打开历史数据
 * */
const openHistoryData = async (record: any) => {
  state.curOlder = record || {};
  state.openHistoryDataVisible = true;
};
/**
 * 全屏
 * */
const fullscreen = () => {
  const {enter, exit} = useFullscreen(dom);
  enter();
};
const showAlarmList = ref(false);
//按信息筛选
const infoFilter = reactive({
  olderName: undefined, //老人姓名
  bedStatus: undefined, //床位状态
  bedStatusButtons: [
    {label: '全部', value: '0', selected: true},
    {label: '正常', value: '1', selected: false},
    {label: '异常', value: '-1', selected: false},
  ],
});
//选择了床位筛选
const selectedBedBtn = (item) => {
  infoFilter.bedStatusButtons.forEach((i) => (i.selected = false));
  item.selected = true;
};
const expandedKeys = ref<string[]>(['0-0-0']);
const selectedKeys = ref<string[]>([]);
const fieldNames: any = {
  title: 'constName',
  key: 'constCode',
};
/**
 *切换左侧菜单
 * */
const selectLeftTab = (type) => {
  curTab.value = type;
};
/**
 *布局自适应
 * */
const layoutAdaptive = () => {
  dom = document.getElementById('realTimeData') as HTMLElement;
  setTimeout(() => {
    state.customStyle = intelligenceAdaptiveLayout({
      container: autoLayoutRef.value,
      autoMargin: true,
      minWidth: 300,
      maxWidth: 300,
      padding: '0.5%',
    });
  }, 0);

  window.addEventListener(
      'resize',
      () => {
        state.customStyle = intelligenceAdaptiveLayout({
          container: autoLayoutRef.value,
          autoMargin: true,
          minWidth: 300,
          maxWidth: 301,
          padding: '0.5%',
        });
        // }, 0)
      },
      false,
  );
};
</script>